import { defineStore } from 'pinia'
import { accountLogin, getUserInfoById, getUserMenuByRoleId } from '@/service/login'
import { ElMessage } from 'element-plus'

import type { IAccount } from '@/types'
import { localCache } from '@/utils/cache'
import router from '@/router'
import { mapMenusToPermissions, mapMenusToRoutes } from '@/utils/map-menus'
import useMainStore from './main'

interface ILoginState {
  token: string
  userInfo: any
  userMenus: []
  permissions: string[]
}
const useLoginStore = defineStore('login', {
  state: (): ILoginState => ({
    token: '',
    userInfo: {},
    userMenus: [],
    permissions: []
  }),
  actions: {
    async loginAccountAction(account: IAccount) {
      try {
        // const res = await accountLogin(account)
        const res = await accountLogin({ name: 'coderwhy', password: '123456' })
        if (res.code === 0) {
          ElMessage.success('登录成功')
          const id = res.data.id
          this.token = res.data.token

          localCache.setCache('token', this.token)
          const unserInfoRes = await getUserInfoById(id)
          const userInfo = unserInfoRes.data
          this.userInfo = unserInfoRes.data
          const menuRes = await getUserMenuByRoleId(this.userInfo.role.id)
          const userMenus = menuRes.data
          this.userMenus = menuRes.data

          localCache.setCache('userInfo', userInfo)
          localCache.setCache('userMenus', userMenus)

          const mainStore = useMainStore()
          mainStore.fetchEntireDataAction()

          // 获取登录用户的所有权限
          const permissions = mapMenusToPermissions(userMenus)
          this.permissions = permissions

          // 动态添加路由
          const routes = mapMenusToRoutes(userMenus)
          routes.forEach((route) => router.addRoute('main', route))

          router.push('/main')
        } else {
          ElMessage.error('登录失败.')
        }
      } catch (e) {
        console.log(e)
      }
    },
    loadLocalCacheAction() {
      const token = localCache.getCache('token')
      const userInfo = localCache.getCache('userInfo')
      const userMenus = localCache.getCache('userMenus')
      if (token && userInfo && userMenus) {
        this.token = token
        this.userInfo = userInfo
        this.userMenus = userMenus

        const permissions = mapMenusToPermissions(userMenus)
        this.permissions = permissions

        // 动态添加路由
        const routes = mapMenusToRoutes(userMenus)
        routes.forEach((route) => router.addRoute('main', route))
      }
    }
  }
})

export default useLoginStore
